<template>
  <div>
    <Row>
      <Col :span="6">
        <Button @click="back2Task" class="backButton">返回</Button>
        <Select
          v-model="selectedTask.taskId"
          style="width: 200px"
          placeholder="可选任务..."
          @on-change="changeTaskInfo"
        >
          <Option
            v-for="item in taskDoing"
            :value="item.taskId"
            :key="item.taskId"
            >{{ item.name }}</Option
          >
        </Select>
      </Col>
      <Col :span="12">
        <div>
          <i-menu
            mode="horizontal"
            :theme="theme1"
            :active-name="menuIndex"
            @on-select="changeMenuItem"
          >
            <menu-item
              :name="item.id"
              style="
                margin-left: 20px;
                width: 180px;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              "
              v-for="(item, index) in taskResList"
              :key="index"
              :title="item.name"
            >
              <Icon type="ios-paper" />
              {{ item.name }}
            </menu-item>
          </i-menu>
        </div>
      </Col>
      <Col :span="5">
        <Button @click="turn2Folder" class="folderButton" v-if="taskInfo.type == 'homework'">提交作业</Button>
      </Col>
    </Row>
    <div class="previewBox" v-if="previewModalShow">
      <vue-scroll :ops="scrollOps" style="height: 90%">
        <iframe
          v-if="previewType != 'txt' && previewType != 'mp4'"
          :src="previewUrl"
          frameborder="0"
          style="width: 95%; height: 100%; min-height: 650px"
        ></iframe>
        <video-player
          class="video-player vjs-custom-skin"
          ref="videoPlayer"
          :playsinline="true"
          :options="playerOptions"
          style="height: 70%; width: 65%; margin-left: 14%;"
          v-if="videoUrlFinished && previewType == 'mp4'"
        >
        </video-player>
        <div
          v-if="previewType == 'txt'"
          style="
            width: 95%;
            height: 100%;
            min-height: 650px;
            font-size: 18px;
            margin-top: 20px;
          "
        >
          {{ previewUrl }}
        </div>
      </vue-scroll>
    </div>
  </div>
</template>

<script>
import { get, post, del, put } from "@/axios";
import { videoPlayer } from 'vue-video-player';
import 'video.js/dist/video-js.css';
export default {
  props: ["taskInfo", "taskDoing"],
  components: {
    videoPlayer,
  },
  data() {
    return {
      scrollOps: {
        bar: {
          background: "#808080",
          keepShow: true,
          size: "8px",
        },
        rail: {
          background: "#d7d7d7",
          opacity: 0.8,
          size: "10px",
        },
      },
      playerOptions: {
        playbackRates: [0.5, 1.0, 1.5, 2.0], // 可选的播放速度
        autoplay: false, // 如果为true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 是否视频一结束就重新开始。
        preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: "zh-CN",
        aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [{
            type: "video/mp4", // 类型
            src: "", // url地址
          },],
        poster: "", // 封面地址
        notSupportedMessage: "此视频暂无法播放，请稍后再试", // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true, // 当前时间和持续时间的分隔符
          durationDisplay: true, // 显示持续时间
          remainingTimeDisplay: true, // 是否显示剩余时间功能
          fullscreenToggle: true, // 是否显示全屏按钮
        },
        replyTarget: "",
      },
      videoUrlFinished: false,
      theme1: "light",
      selectedTask: JSON.parse(JSON.stringify(this.taskInfo)),
      taskResList: [],
      menuIndex: 0,
      previewUrl: "",
      previewType: "",
      dataSever: "",
      previewModalShow: false,
      tempFile: null,
    };
  },
  watch: {
    // taskInfo() {
    //   console.log(this.taskInfo);
    //   this.selectedTask = JSON.parse(JSON.stringify(this.taskInfo));
    // },
  },
  created() {},
  mounted() {
    this.dataSever = this.$store.getters.dataSever;
    this.getTaskContents();
  },
  methods: {
    async getTaskContents() {
      //由于该task中的资源 全部存储在与taskId同id的文件夹下，所以只需要获取文件夹下的资源
      // 需要筛选 判断是属于绑定在task中的资源还是 后期向文件夹中上传的文件
      // 绑定在task中的资源 其id都存储在task.contents 中
      let reqInfo = {
        asc: false,
        page: 0,
        pageSize: 50,
      };
      try {
        let res = await post(
          "/visualResourceLibrary/res/resource/browse/" +
            this.selectedTask.taskId,
          reqInfo
        );
        let rootRes = res.data.data;
        this.taskResList = [];
        for (let i = 0; i < rootRes.total; i++) {
          if (
            this.selectedTask.contents
              .toString()
              .indexOf(rootRes.content[i].id) != -1
          ) {
            this.taskResList.push(rootRes.content[i]);
          }
        }
        this.menuIndex = this.taskResList[0].id;
        // console.log(this.taskResList);
        this.preview();
      } catch (e) {
        console.log(e);
      }
    },
    changeMenuItem(value) {
      this.menuIndex = value;
      // console.log(this.menuIndex);
      //   this.previewModalShow = false;
      this.preview();
    },
    changeTaskInfo(value) {
      for (let i = 0; i < this.taskDoing.length; i++) {
        if (value == this.taskDoing[i].taskId) {
          this.selectedTask = JSON.parse(JSON.stringify(this.taskDoing[i]));
          this.getTaskContents();
        }
      }
    },
    preview() {
      let url = this.dataSever;
      let resStr = "";
      let suffix = "";
      for (let i = 0; i < this.taskResList.length; i++) {
        if (this.taskResList[i].id == this.menuIndex) {
          resStr = this.taskResList[i].url;
          suffix = this.taskResList[i].suffix;
        }
      }
      if (resStr.indexOf("resRepository") != -1) {
        resStr = "resRepository" + resStr.split("resRepository")[1];
        url = url + resStr;
        this.previewType = suffix;
        if (suffix == "txt") {
          // console.log(url);
          this.previewType = "txt";
          let value = this.getTxtFile(url);
          value.then((result) => {
            const that = this;
            var reader = new FileReader();
            reader.readAsText(result);
            reader.onload = function (event) {
              that.previewUrl = reader.result;
              // console.log(reader.result);
            };
          });

          // console.log(value);
          // this.previewUrl = value;
        } else if(suffix == "mp4"){
          this.playerOptions.sources[0].src = url;
          this.videoUrlFinished = true;
        } else {
          this.previewUrl = url;
        }
        this.previewModalShow = true;
      }
    },
    getTxtFile(url) {
      return new Promise((resolve, reject) => {
        var blob = null;
        var xhr = new XMLHttpRequest();
        xhr.open("GET", url);
        xhr.setRequestHeader("Accept", "text/html");
        xhr.responseType = "blob";
        xhr.onload = () => {
          blob = xhr.response;
          let tempFile = new File([blob], "tempTxt", { type: "text/html" });
          resolve(tempFile);
        };
        xhr.onerror = (e) => {
          reject(e);
        };
        xhr.send();
      });
    },
    back2Task() {
      this.$emit("back2Task");
    },
    turn2Folder() {
      this.$emit("turn2Folder", this.taskInfo.taskId);
    }
  },
};
</script>

<style>
.backButton {
  margin-left: 20px;
}
.folderButton{
  float: right;
  margin-right: 10px;
}
.previewBox {
  width: 90vw;
  height: 75vh;
  margin-left: 3%;
}
</style>